package com.ruoyi.system.task;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.enums.LivePlayBackEvenNameEnum;
import com.ruoyi.common.core.enums.PlayerLogType;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.BaseLivePlayBackEven;
import com.ruoyi.system.domain.BasePlayerLog;
import com.ruoyi.system.domain.BaseTournament;
import com.ruoyi.system.service.IBaseLivePlayBackEvenService;
import com.ruoyi.system.service.IBasePlayerLogService;
import com.ruoyi.system.service.IBaseTournamentService;
import com.ruoyi.system.service.impl.LiveService;
import com.ruoyi.system.service.impl.LoginUserSetUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.mps.v20190612.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class BaseLivePlayBackEvenJob {
    @Resource
    private IBaseLivePlayBackEvenService iBaseLivePlayBackEvenService;
    @Resource
    LoginUserSetUtil loginUserSetUtil;
    @Resource
    private LiveService liveService;
    @Resource
    private IBasePlayerLogService iBasePlayerLogService;
    @Resource
    private IBaseTournamentService iBaseTournamentService;
    @Scheduled(cron = "0 0/30 * * * ?")
//    @Scheduled(cron = "30 * * * * ?")
    private void task() {

        List<BaseLivePlayBackEven> list = iBaseLivePlayBackEvenService.list(Wrappers.<BaseLivePlayBackEven>lambdaQuery()
                .eq(BaseLivePlayBackEven::getStatus, 0)
                .ne(BaseLivePlayBackEven::getName, LivePlayBackEvenNameEnum.LIVE_REPLAY.getName())
                .ne(BaseLivePlayBackEven::getName, LivePlayBackEvenNameEnum.GAME_SUMMARY.getName())
                .ne(BaseLivePlayBackEven::getName,LivePlayBackEvenNameEnum.PERSONAL_HIGHLIGHTS.getName())
                .eq(BaseLivePlayBackEven::getIsDeleted,0)
        );
        log.info("时移固化定时器开始执行，修正【{}】个",list.size());
        if (CollUtil.isEmpty(list)){
            return;
        }
        list.forEach(vo ->{
            ProcessMediaResponse response = liveService.ProcessMedia(vo.getVideoUrl());
            if (Objects.nonNull(response) && Objects.nonNull(response.getTaskId())){
                vo.setTaskId(response.getTaskId());
                vo.setStatus(1);
            }
        });
        iBaseLivePlayBackEvenService.updateBatchById(list);
    }

    @Scheduled(cron = "0 0/10 * * * ?")
//    @Scheduled(cron = "30 * * * * ?")
    private void taskTwo() {
        List<BaseLivePlayBackEven> list = iBaseLivePlayBackEvenService.list(Wrappers.<BaseLivePlayBackEven>lambdaQuery()
                .eq(BaseLivePlayBackEven::getStatus, 1)
                .ne(BaseLivePlayBackEven::getName,LivePlayBackEvenNameEnum.LIVE_REPLAY.getName())
                .eq(BaseLivePlayBackEven::getIsDeleted,0)
        );
        log.info("查询时移固化定时器开始执行，修正【{}】个",list.size());
        if (CollUtil.isEmpty(list)){
            return;
        }
        list.forEach(vo ->{

            DescribeTaskDetailResponse response = liveService.DescribeTaskDetail(vo.getTaskId());
            if (Objects.nonNull(response)){
                if (response.getTaskType().equals("EditMediaTask")){
                    EditMediaTask editMediaTask = response.getEditMediaTask();
                    if (Objects.nonNull(editMediaTask)){
                        EditMediaTaskOutput output = editMediaTask.getOutput();
                        if (Objects.nonNull(output)){
                            if (vo.getName().equals(LivePlayBackEvenNameEnum.PERSONAL_HIGHLIGHTS.getName())){
                                String url = StringUtils.isNoneBlank(output.getPath())?output.getPath():"/file/all_EditMedia_"+vo.getTournamentId().toString()+vo.getPlayId().toString()+".mp4";
                                vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com"+url);
                            }else{
                                String url = StringUtils.isNoneBlank(output.getPath())?output.getPath():"/file/all_EditMedia_"+vo.getTournamentId()+".mp4";
                                vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com"+url);
                            }
                            vo.setStatus(3);
                        }
                    }
                }else{
                    ScheduleTask scheduleTask = response.getScheduleTask();
                    if (Objects.nonNull(scheduleTask)){
                        ActivityResult[] activityResultSet = scheduleTask.getActivityResultSet();
                        ActivityResult activityResult = activityResultSet[0];
                        if (Objects.nonNull(activityResult)){
                            ActivityResItem activityResItem = activityResult.getActivityResItem();
                            if (Objects.nonNull(activityResItem)){
                                MediaProcessTaskTranscodeResult transcodeTask = activityResItem.getTranscodeTask();
                                if (Objects.nonNull(transcodeTask)){
                                    MediaTranscodeItem output = transcodeTask.getOutput();
                                    if (Objects.nonNull(output)){
                                        String url = StringUtils.isNoneBlank(output.getPath())?output.getPath():"/file/all_EditMedia_"+vo.getTournamentId()+".mp4";
                                        vo.setVideoUrl("https://ydsg-1256672631.cos.ap-guangzhou.myqcloud.com"+url);
                                        if (Objects.equals(vo.getName(),"二分命中") || Objects.equals(vo.getName(),"三分命中")
                                            || Objects.equals(vo.getName(),"一分命中") || Objects.equals(vo.getName(),"罚球命中")){
                                            vo.setStatus(2);
                                        }else{
                                            vo.setStatus(3);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }else{
                vo.setStatus(0);
                vo.setVideoUrl("");
            }
        });
        List<BaseLivePlayBackEven> collect = list.stream().filter(o -> Objects.equals(o.getStatus(), 2) || Objects.equals(o.getStatus(), 3)).collect(Collectors.toList());
        iBaseLivePlayBackEvenService.updateBatchById(collect);
    }
    private static Map<Long, Long> scoreMap = new HashMap<>();

    static {
        //二分
        scoreMap.put(PlayerLogType.TWO_POINT_HIT.getCode(), 2L);
        //三分
        scoreMap.put(PlayerLogType.THREE_POINT_HIT.getCode(), 3L);
        //一分
        scoreMap.put(PlayerLogType.ONE_POINT_HIT.getCode(), 1L);
        //罚球
        scoreMap.put(PlayerLogType.POINT_HIT.getCode(), 1L);
    }
    @Scheduled(cron = "0 0 0/1 * * ? ")
//    @Scheduled(cron = "30 * * * * ?")
    private void task3() throws TencentCloudSDKException {
        List<BaseLivePlayBackEven> list = iBaseLivePlayBackEvenService.list(Wrappers.<BaseLivePlayBackEven>lambdaQuery()
                .eq(BaseLivePlayBackEven::getStatus, 2)
                .in(BaseLivePlayBackEven::getName,"二分命中","三分命中","一分命中","罚球命中")
                .eq(BaseLivePlayBackEven::getIsDeleted,0)
        );
        list = list.stream().collect(Collectors.collectingAndThen
                (Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing
                        (BaseLivePlayBackEven::getPlayerLogId))), ArrayList::new));
         if (CollUtil.isEmpty(list)){
            return;
        }
        List<Long> collect2 = list.stream().map(BaseLivePlayBackEven::getPlayerLogId).collect(Collectors.toList());

         //过滤比赛得分合成锦集
        List<BasePlayerLog> playerLogList = iBasePlayerLogService.getBaseMapper().selectBatchIds(collect2);
        if (CollUtil.isEmpty(playerLogList)){
            return;
        }
        List<Long> collect3 = playerLogList.stream().filter(vo -> scoreMap.keySet().contains(vo.getType())).map(BasePlayerLog::getId).collect(Collectors.toList());
        list = list.stream().filter(vo -> collect3.contains(vo.getPlayerLogId())).collect(Collectors.toList());
        if (CollUtil.isEmpty(list)){
            return;
        }
        //获取比赛已结束的 视频进行固化
        List<Long> tournamentIds = list.stream().map(BaseLivePlayBackEven::getTournamentId).collect(Collectors.toList());
        //处理结束比赛之后 30分钟之后的比赛
        Calendar instance = Calendar.getInstance();
        instance.setTime(new Date());
        instance.add(Calendar.MINUTE,-30);
        Date time = instance.getTime();
        List<BaseTournament> tournamentList = iBaseTournamentService.selectByIdsAndState(tournamentIds,2,time);
        List<Long> collect4 = tournamentList.stream().map(BaseTournament::getId).collect(Collectors.toList());
        list = list.stream().filter(o -> collect4.contains(o.getTournamentId())).collect(Collectors.toList());
        if (CollUtil.isEmpty(list)){
            return;
        }
        log.info("精彩集锦定时器开始执行，修正【{}】个",list.size());
        List<BaseLivePlayBackEven> evenList = new ArrayList<>();
        Map<Long, List<BaseLivePlayBackEven>> collect = list.stream().collect(Collectors.groupingBy(BaseLivePlayBackEven::getTournamentId));
        for (Map.Entry<Long, List<BaseLivePlayBackEven>> key:collect.entrySet()) {
            Long key1 = key.getKey();
            //合成球员锦集
            List<BaseLivePlayBackEven> value = key.getValue();
            Map<Long, List<BaseLivePlayBackEven>> collect1 = value.stream().collect(Collectors.groupingBy(BaseLivePlayBackEven::getPlayId));
            for (Map.Entry<Long, List<BaseLivePlayBackEven>> player:collect1.entrySet()) {
                EditMediaResponse response = liveService.EditMedia(player.getValue(),key.getKey().toString()+player.getKey().toString());
                if (Objects.nonNull(response) && Objects.nonNull(response.getTaskId())){
                    BaseLivePlayBackEven even = new BaseLivePlayBackEven();
                    even.setTaskId(response.getTaskId());
                    even.setPlayId(player.getKey());
                    even.setStatus(1);
                    even.setTournamentId(key1);
                    even.setName(LivePlayBackEvenNameEnum.PERSONAL_HIGHLIGHTS.getName());
                    even.setCreateTime(new Date());
                    evenList.add(even);
                }
            }
            EditMediaResponse response = liveService.EditMedia(key.getValue(),key.getKey().toString());
            if (Objects.nonNull(response) && Objects.nonNull(response.getTaskId())){
                    BaseLivePlayBackEven even = new BaseLivePlayBackEven();
                    even.setTaskId(response.getTaskId());
                    even.setStatus(1);
                    even.setTournamentId(key1);
                    even.setName(LivePlayBackEvenNameEnum.GAME_SUMMARY.getName());
                    even.setCreateTime(new Date());
                    evenList.add(even);
            }
        }
        List<Long> collect1 = evenList.stream().map(BaseLivePlayBackEven::getTournamentId).collect(Collectors.toList());
        iBaseLivePlayBackEvenService.update(Wrappers.<BaseLivePlayBackEven>lambdaUpdate()
                .set(BaseLivePlayBackEven::getStatus,3)
                .ne(BaseLivePlayBackEven::getName,LivePlayBackEvenNameEnum.LIVE_REPLAY.getName())
                .ne(BaseLivePlayBackEven::getName,LivePlayBackEvenNameEnum.GAME_SUMMARY.getName())
                .ne(BaseLivePlayBackEven::getName,LivePlayBackEvenNameEnum.PERSONAL_HIGHLIGHTS.getName())
                .in(BaseLivePlayBackEven::getTournamentId,collect1));
        iBaseLivePlayBackEvenService.saveBatch(evenList);
    }
}
